<template>
    <div id="login-modal" class="modal fade" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body">

                    <div class="login-div" v-show="MODAL_STATUS === STATUS_LOGIN">
                        <h3>登&nbsp;&nbsp;录</h3>
                        <div class="form-group">
                            <input v-model="user.userName" class="form-control" placeholder="用户名">
                        </div>
                        <div class="form-group">
                            <input id="password" v-model="user.password" type="password" class="form-control" placeholder="密码">
                        </div>
                        <div class="form-group">
                            <div class="input-group">
                                <input id="image-code-input" class="form-control" type="text" placeholder="验证码"
                                    v-model="user.imageCode">
                                <div class="input-group-addon" id="image-code-addon">
                                    <img id="image-code" alt="验证码" src="" v-on:click="loadImageCode()" />
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <button v-on:click="login()" class="btn btn-primary btn-block submit-button">
                                登&nbsp;&nbsp;录
                            </button>
                        </div>
                        <div class="form-group">
                            <div class="checkbox">
                                <label>
                                    <input type="checkbox" class="remember" v-model="remember">&nbsp;记住密码
                                </label>
                                <div class="pull-right">
                                    <a href="javascript:;" v-on:click="toForgetDiv()">忘记密码</a>&nbsp;
                                    <a href="javascript:;" v-on:click="toRegisterDiv()">我要注册</a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="register-div" v-show="MODAL_STATUS === STATUS_REGISTER">
                        <h3>注&nbsp;&nbsp;册</h3>
                        <div class="form-group">
                            <input v-on:blur="onRegisterEmailBlur()"
                                   v-bind:class="registerEmailValidateClass"
                                   id="register-email" v-model="userRegister.email"
                                   class="form-control" placeholder="邮箱">
                            <span v-show="registerEmailValidate === false" class="text-danger">邮箱格式必须为example@xxx.xx</span>
                        </div>
                        <div class="form-group">
                            <div class="input-group">
                                <input v-on:blur="onRegisterEmailCodeBlur()"
                                       v-bind:class="registerEmailCodeValidateClass"
                                       id="register-email-code" class="form-control"
                                       placeholder="邮箱验证码" v-model="userRegister.emailCode">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" id="register-send-code-btn"
                                        v-on:click="sendEcodeForRegister()">发送验证码</button>
                                </div>
                            </div>
                            <span v-show="registerEmailCodeValidate === false" class="text-danger">验证码必须是6位数字</span>
                        </div>
                        <div class="form-group">
                            <input v-on:blur="onRegisterUserNameBlur()"
                                   v-bind:class="registerUserNameValidateClass"
                                   id="register-user-name" v-model="userRegister.userName"
                                   class="form-control" placeholder="用户名">
                            <span v-show="registerUserNameValidate === false" class="text-danger">用户名2到16位字母，数字，下划线组合</span>
                            <span v-show="registerUserNameExistsValidate === false" class="text-danger">该用户名已存在，不能重复注册</span>
                        </div>
                        <div class="form-group">
                            <input v-on:blur="onRegisterNameBlur()"
                                   v-bind:class="registerNameValidateClass"
                                   id="register-name" v-model="userRegister.name"
                                   class="form-control" placeholder="昵称">
                            <span v-show="registerNameValidate === false" class="text-danger">昵称2到20位中文，字母，数字，下划线组合</span>
                        </div>
                        <div class="form-group">
                            <input v-on:blur="onRegisterPasswordBlur()"
                                   v-bind:class="registerPasswordValidateClass"
                                   id="register-password" v-model="userRegister.passwordOriginal"
                                   class="form-control" type="password" placeholder="密码">
                            <span v-show="registerPasswordValidate === false" class="text-danger">密码最少6位，包含至少1字母和1个数字</span>
                        </div>
                        <div class="form-group">
                            <input v-on:blur="onRegisterConfirmPasswordBlur()"
                                   v-bind:class="registerConfirmPasswordValidateClass"
                                   id="register-confirm-password" v-model="userRegister.passwordConfirm"
                                   class="form-control" type="password" placeholder="确认密码">
                        </div>
                        <span v-show="registerConfirmPasswordValidate === false" class="text-danger">确认密码和密码不一致!</span>
                        <div class="form-group">
                            <button class="btn btn-primary btn-block submit-button" v-on:click="register()">
                                注册
                            </button>
                        </div>
                        <div class="form-group to-login-div">
                            <a href="javascript:;" v-on:click="toLoginDiv()">我要登录</a>
                        </div>
                    </div>

                    <div class="forget-div" v-show="MODAL_STATUS === STATUS_FORGET">
                        <h3>忘记密码</h3>
                        <div class="form-group">
                            <input v-on:blur="onForgetEmailBlur()"
                                   v-bind:class="forgetEmailValidateClass"
                                   id="forget-email" v-model="userForget.email"
                                class="form-control" placeholder="邮箱">
                            <span v-show="forgetEmailValidate === false" class="text-danger">邮箱格式要求正确，且必须已注册</span>
                        </div>
                        <div class="form-group">
                            <div class="input-group">
                                <input v-on:blur="onForgetEmailCodeBlur()"
                                       v-bind:class="forgetEmailCodeValidateClass"
                                       id="forget-email-code" class="form-control"
                                       placeholder="邮箱验证码" v-model="userForget.emailCode">
                                <div class="input-group-append">
                                    <button v-on:click="sendEcodeForForget()"
                                            class="btn btn-outline-secondary" id="forget-send-code-btn">
                                        发送验证码
                                    </button>
                                </div>
                            </div>
                            <span v-show="forgetEmailCodeValidate === false" class="text-danger">验证码必须是6位数字</span>
                        </div>
                        <div class="form-group">
                            <input v-on:blur="onForgetPasswordBlur()"
                                   v-bind:class="forgetPasswordValidateClass"
                                   id="forget-password" v-model="userForget.passwordOriginal"
                                   class="form-control" type="password" placeholder="密码">
                            <span v-show="forgetPasswordValidate === false" class="text-danger">密码最少6位，包含至少1字母和1个数字</span>
                        </div>
                        <div class="form-group">
                            <input v-on:blur="onForgetConfirmPasswordBlur()"
                                   v-bind:class="forgetConfirmPasswordValidateClass"
                                   id="forget-confirm-password" v-model="userForget.passwordConfirm"
                                   class="form-control" type="password" placeholder="确认密码">
                            <span v-show="forgetConfirmPasswordValidate === false" class="text-danger">确认密码和密码不一致!</span>
                        </div>
                        <div class="form-group">
                            <button v-on:click="resetPassword()" class="btn btn-primary btn-block submit-button">
                                重&nbsp;&nbsp;置
                            </button>
                        </div>
                        <div class="form-group to-login-div">
                            <a href="javascript:;" v-on:click="toLoginDiv()">我要登录</a>
                        </div>
                    </div>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
</template>

<script>
    export default {
        name: "The-Login",
        data: function () {
            return {
                STATUS_LOGIN: "STATUS_LOGIN",
                STATUS_REGISTER: "STATUS_REGISTER",
                STATUS_FORGET: "STATUS_FORGET",
                MODAL_STATUS: "",

                user: {},
                userForget: {},
                userRegister: {},
                remember: false,
                imageCodeToken: "",
                defaultPhotos: [],

                countdown: 0,

                registerEmailValidate: true,  // 注册手机号校验结果
                registerEmailCodeValidate: true,  // 手机验证码校验结果
                registerUserNameValidate: true,  // 用户名校验结果
                registerNameValidate: true,  // 昵称校验结果
                registerPasswordValidate: true,  // 密码校验结果
                registerConfirmPasswordValidate: true,  // 确认密码校验结果
                registerUserNameExistsValidate: true, // 用户名是否已被注册结果

                forgetEmailValidate: true,
                forgetEmailCodeValidate: true,
                forgetPasswordValidate: true,
                forgetConfirmPasswordValidate: true,

            }
        },
        mounted() {
            let _this = this;
            _this.toLoginDiv();
            // 监听事件总线
            _this.$event.$on("openLoginModal", function () {
                _this.openLoginModal();
            });

            $('#image-code-input').on('keypress',function(event){
                if(event.keyCode === 13) {
                    _this.login();
                }
            });
            $('#password').on('keypress',function(event){
                if(event.keyCode === 13) {
                    _this.login();
                }
            });
        },
        computed: {
            // -------------注册------------------
            registerEmailValidateClass(){
                return {
                    'border-success': this.registerEmailValidate === true,
                    'border-danger': this.registerEmailValidate === false,
                }
            },
            registerEmailCodeValidateClass(){
                return {
                    'border-success': this.registerEmailCodeValidate === true,
                    'border-danger': this.registerEmailCodeValidate === false,
                }
            },
            registerUserNameValidateClass(){
                return {
                    'border-success': this.registerUserNameValidate === true && this.registerUserNameExistsValidate === true,
                    'border-danger': this.registerUserNameValidate === false || this.registerUserNameExistsValidate === false,
                }
            },
            registerNameValidateClass(){
                return {
                    'border-success': this.registerNameValidate === true,
                    'border-danger': this.registerNameValidate === false,
                }
            },
            registerPasswordValidateClass(){
                return {
                    'border-success': this.registerPasswordValidate === true,
                    'border-danger': this.registerPasswordValidate === false,
                }
            },
            registerConfirmPasswordValidateClass(){
                return {
                    'border-success': this.registerConfirmPasswordValidate === true,
                    'border-danger': this.registerConfirmPasswordValidate === false,
                }
            },

            // ---------------忘记密码-----------------
            forgetEmailValidateClass(){
                return {
                    'border-success': this.forgetEmailValidate === true,
                    'border-danger': this.forgetEmailValidate === false,
                }
            },
            forgetEmailCodeValidateClass(){
                return {
                    'border-success': this.forgetEmailCodeValidate === true,
                    'border-danger': this.forgetEmailCodeValidate === false,
                }
            },
            forgetPasswordValidateClass(){
                return {
                    'border-success': this.forgetPasswordValidate === true,
                    'border-danger': this.forgetPasswordValidate === false,
                }
            },
            forgetConfirmPasswordValidateClass(){
                return {
                    'border-success': this.forgetConfirmPasswordValidate === true,
                    'border-danger': this.forgetConfirmPasswordValidate === false,
                }
            },
        },
        methods: {
            openLoginModal(){
                let _this = this;
                _this.toLoginDiv();
                $("#login-modal").modal("show");
            },

            // -----------------登录框、注册框、忘记密码框之间切换------------------
            toLoginDiv(){
                let _this = this;

                let rememberUser = LocalStorage.get(LOCAL_KEY_REMEMBER);
                if(rememberUser){
                    _this.user = rememberUser;
                }
                // 从localStorage里得到上次有没有勾选“记住我”
                _this.remember = LocalStorage.get(LOCAL_KEY_REMEMBER_CHECKBOX) || false;
                _this.user.imageCode = null;
                _this.loadImageCode();
                _this.MODAL_STATUS = _this.STATUS_LOGIN;
            },
            toRegisterDiv(){
                let _this = this;
                _this.MODAL_STATUS = _this.STATUS_REGISTER;

                _this.$ajax.get(process.env.VUE_APP_SERVER + '/file/file/get-default-photo').then(response=>{
                    let resp = response.data;
                    if(resp.success){
                        _this.defaultPhotos = resp.content;
                    }
                })
            },
            toForgetDiv(){
                let _this = this;
                _this.MODAL_STATUS = _this.STATUS_FORGET;
            },

            register(){
                let _this = this;

                // 校验所有输入框
                if(!(_this.onRegisterEmailBlur()
                        && _this.onRegisterEmailCodeBlur()
                        && _this.onRegisterNameBlur()
                        && _this.onRegisterPasswordBlur()
                        && _this.onRegisterConfirmPasswordBlur())
                ){

                    return;
                }

                if(_this.defaultPhotos.length !== 0){
                    let index = Math.floor(Math.random() * _this.defaultPhotos.length);
                    _this.userRegister.photo = _this.defaultPhotos[index];
                }

                _this.userRegister.password = hex_md5(_this.userRegister.passwordOriginal + KEY);

                _this.$ajax.post(process.env.VUE_APP_SERVER + '/user/user/register', _this.userRegister).then(response=>{
                    let resp = response.data;
                    if(resp.success){
                        Toast.success("注册成功");
                        _this.toLoginDiv();
                        _this.userRegister = {};
                        _this.registerUserNameExistsValidate = true;
                    }else{
                        if(resp.code === RESP_CODE.USER_NAME_EXISTS){
                            _this.registerUserNameExistsValidate = false;
                        }else{
                            _this.registerUserNameExistsValidate = true;
                        }
                        Toast.warning(resp.message);
                    }
                })
            },

            // ------------登录框-------------
            /**
             * 加载图形验证码
             */
            loadImageCode(){
                let _this = this;
                _this.imageCodeToken = Tool.uuid(8);
                $("#image-code").attr('src', process.env.VUE_APP_SERVER + '/user/kaptcha/image-code/' + _this.imageCodeToken);
            },

            login(){
                let _this = this;
                if(1 != 1
                    || !Validator.require(_this.user.userName, "用户名")
                    || !Validator.length(_this.user.userName, "用户名", 2, 16)
                    || !Validator.require(_this.user.password, "密码")
                    || !Validator.require(_this.user.imageCode, "验证码")
                    || !Validator.length(_this.user.imageCode, "验证码",4,4)
                    ) {
                    return;
                }

                // 如果密码是从缓存取出来的，则不需要重新加密
                let md5 = hex_md5(_this.user.password);
                let rememberUser = LocalStorage.get(LOCAL_KEY_REMEMBER) || {};
                if(md5 !== rememberUser.md5){
                    _this.user.password = hex_md5(_this.user.password + KEY);
                }
                _this.user.imageCodeToken = _this.imageCodeToken;

                // 判断操作系统
                var result = Tool.testOS();
                if(result.isAndroid){
                    _this.user.os = "Android";
                }else if(result.isIpad){
                    _this.user.os = "IOS";
                }else if(result.isIphone){
                    _this.user.os = "IOS";
                }else if(result.isMac){
                    _this.user.os = "MacOS";
                }else if(result.isVista){
                    _this.user.os = "vista";
                }else if(result.isWin2K){
                    _this.user.os = "Win 2k";
                }else if(result.isWin7){
                    _this.user.os = "Win 7";
                }else if(result.isWin8){
                    _this.user.os = "Win 8"
                }else if(result.isWin81){
                    _this.user.os = "Win 81";
                }else if(result.isWin10){
                    _this.user.os = "Win 10";
                }else if(result.isWindowsCe){
                    _this.user.os = "Windows ce";
                }else if(result.isWindowsMobile){
                    _this.user.os = "Windows mobile"
                }else if(result.isXP){
                    _this.user.os = "Windows XP";
                }

                _this.$ajax.post(process.env.VUE_APP_SERVER + '/user/user/login',_this.user).then(response=>{

                    let resp = response.data;
                    if(resp.success){
                        let loginUser = resp.content;
                        if(_this.remember){
                            let md5 = hex_md5(_this.user.password);
                            LocalStorage.set(LOCAL_KEY_REMEMBER_CHECKBOX,true);
                            LocalStorage.set(LOCAL_KEY_REMEMBER,{
                                userName: loginUser.userName,
                                password: _this.user.password,
                                md5: md5
                            });
                        }else{
                            LocalStorage.set(LOCAL_KEY_REMEMBER_CHECKBOX,false);
                            LocalStorage.set(LOCAL_KEY_REMEMBER, {
                                userName: loginUser.userName
                            });
                        }
                        // 登录成功
                        _this.$parent.getExpAndLevel(loginUser.id);
                        _this.$parent.setLoginUser(loginUser);
                        $("#login-modal").modal("hide");
                        if (_this.$route.path === '/home') {
                            _this.$event.$emit("getLoginUser");
                        }
                    }else{
                        Toast.warning(resp.message);
                        _this.user.password = "";
                        _this.loadImageCode();
                    }
                })
            },

            /**
             * 发送注册邮件
             */
            sendEcodeForRegister(){
                let _this = this;

                if(!this.onRegisterEmailBlur()){
                    return false;
                }

                let ecode = {
                    email: _this.userRegister.email,
                    use: ECODE_USE.REGISTER.key
                };

                // 先校验邮箱是否已经存在
                _this.$ajax.get(process.env.VUE_APP_SERVER + '/user/user/is-email-exists/'+ecode.email).then(response=>{
                    let resp = response.data;
                    if(resp.success){
                        Toast.warning("邮箱已被注册");
                    }else{
                        _this.sendEmailCode(ecode, "register-send-code-btn");
                    }
                })
            },

            /**
             * 发送短信
             * @param ecode
             */
            sendEmailCode(ecode, btnId){
                let _this = this;

                // 调服务端发送短信接口
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/user/ecode/send', ecode).then(response=>{
                    let resp = response.data;
                    if(resp.success){
                        Toast.success("邮件已发送");
                        // 开始倒计时
                        _this.countdown = 60;
                        _this.setTime(btnId);
                    }else{
                        Toast.warning(resp.message);
                    }
                })
            },

            setTime(btnId){
                let _this = this;
                let btn = $("#" + btnId);
                if(_this.countdown === 0){
                    btn.removeAttr("disabled");
                    btn.text("重新发送");
                    btn.css("cursor","pointer");
                    return;
                }
                btn.attr("disabled",true);
                btn.css("cursor","default");
                btn.text("重新发送 ("+ _this.countdown +"s) ");
                _this.countdown--;
                setTimeout(function () {
                    _this.setTime(btnId);
                }, 1000);
            },

            /**
             * 发送忘记密码邮件
             */
            sendEcodeForForget(){
                let _this = this;

                if(!this.onForgetEmailBlur()){
                    return false;
                }

                let ecode = {
                    email: _this.userForget.email,
                    use: ECODE_USE.FORGET.key
                };

                // 先校验邮箱是否已经存在
                _this.$ajax.get(process.env.VUE_APP_SERVER + '/user/user/is-email-exists/'+ecode.email).then(response=>{
                    let resp = response.data;
                    if(resp.success){
                        _this.forgetEmailValidate = true;
                        _this.sendEmailCode(ecode, "forget-send-code-btn");
                    }else{
                        _this.forgetEmailValidate = false;
                        Toast.warning("邮箱未注册");
                    }
                })
            },

            resetPassword(){
                let _this = this;

                if(!(_this.onForgetEmailBlur()
                        && _this.onForgetEmailCodeBlur()
                        && _this.onForgetPasswordBlur()
                        && _this.onForgetConfirmPasswordBlur())) {
                    return;
                }
                _this.userForget.password = hex_md5(_this.userForget.passwordOriginal + KEY);

                _this.$ajax.post(process.env.VUE_APP_SERVER + '/user/user/reset-password', _this.userForget).then(response=>{
                    let resp = response.data;
                    if(resp.success){
                        Toast.success("重置密码成功");
                        // $("#login-modal").modal("hide");
                        _this.toLoginDiv();
                        _this.userForget = {};
                    }else{
                        Toast.warning(resp.message);
                    }
                })
            },

            // -------------注册框校验---------------
            onRegisterEmailBlur(){
                let _this = this;
                _this.registerEmailValidate = Pattern.validateEmail(_this.userRegister.email);
                return _this.registerEmailValidate;
            },

            /**
             * 短信验证码校验
             * @returns {boolean} 短信验证码校验结果
             */
            onRegisterEmailCodeBlur(){
                let _this = this;
                _this.registerEmailCodeValidate = Pattern.validateEmailCode(_this.userRegister.emailCode);
                return _this.registerEmailCodeValidate;
            },

            /**
             * 用户名校验
             */
            onRegisterUserNameBlur(){
                let _this = this;
                _this.registerUserNameValidate = Pattern.validateLoginName(_this.userRegister.userName);
                return _this.registerUserNameValidate;
            },

            /**
             * 昵称校验
             */
            onRegisterNameBlur(){
                let _this = this;
                _this.registerNameValidate = Pattern.validateName(_this.userRegister.name);
                return _this.registerNameValidate;
            },

            /**
             * 密码校验
             * @returns {boolean}
             */
            onRegisterPasswordBlur(){
                let _this = this;
                _this.registerPasswordValidate = Pattern.validatePasswordWeak(_this.userRegister.passwordOriginal);
                return _this.registerPasswordValidate;
            },

            onRegisterConfirmPasswordBlur(){
                let _this = this;
                let confirmPassword = $("#register-confirm-password").val();
                if(Tool.isEmpty(confirmPassword)){
                    return _this.registerConfirmPasswordValidate = false;
                }
                return _this.registerConfirmPasswordValidate = (confirmPassword === _this.userRegister.passwordOriginal)
            },

            // ---------------忘记密码框校验-----------------
            onForgetEmailBlur(){
                let _this = this;
                _this.forgetEmailValidate = Pattern.validateEmail(_this.userForget.email);
                return _this.forgetEmailValidate;
            },
            onForgetEmailCodeBlur(){
                let _this = this;
                _this.forgetEmailCodeValidate = Pattern.validateEmailCode(_this.userForget.emailCode);
                return _this.forgetEmailCodeValidate;
            },
            onForgetPasswordBlur(){
                let _this = this;
                _this.forgetPasswordValidate = Pattern.validatePasswordWeak(_this.userForget.passwordOriginal);
                return _this.forgetPasswordValidate;
            },
            onForgetConfirmPasswordBlur(){
                let _this = this;
                let confirmPassword = $("#forget-confirm-password").val();
                if(Tool.isEmpty(confirmPassword)){
                    return _this.forgetConfirmPasswordValidate = false;
                }
                return _this.forgetConfirmPasswordValidate = (confirmPassword === _this.userForget.passwordOriginal)
            }
        }
    }
</script>

<style scoped>
    /* 登录框 */
    .login-div .input-group-addon {
        padding: 0;
        border: 0;
    }

    #login-modal h3 {
        text-align: center;
        margin-bottom: 20px;
    }

    #login-modal .modal-login {
        max-width: 400px;
    }

    #login-modal input:not(.remember) {
        height: 45px;
        font-size: 16px;
    }

    #login-modal .submit-button {
        height: 50px;
        font-size: 20px;
    }

    #login-modal .to-login-div {
        text-align: center;
    }
</style>